#include <stdio.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/shm.h>

int main(int argc,char* argv[])
{
	key_t key, key1;
	int id, semid;
	char *ptr;
	struct sembuf sops[6];
	short arr[3] = {0, 8, 1};
	union semun
	{
		int value;
		struct semid_ds *buf;
		unsigned short *array;
	} arg;
	key = ftok("/home/ff/code/linux/test_24_11_11", 'a');
	key1 = ftok("/", 'b');
	semid = semget(key1, 3, IPC_CREAT | 0666);
	id = shmget(key, 1024, IPC_CREAT | 0666);
	ptr = (char *)shmat(id, NULL, 0);
	// set sems original value
	arg.array = arr;
	semctl(semid, 0, SETALL, arg);
	// P(pronum)
	sops[0].sem_num = 0;
	sops[0].sem_op = -1;
	sops[0].sem_flg = SEM_UNDO;
	// P(space)
	sops[1].sem_num = 1;
	sops[1].sem_op = -1;
	sops[1].sem_flg = SEM_UNDO;
	// P(lock)
	sops[2].sem_num = 2;
	sops[2].sem_op = -1;
	sops[2].sem_flg = SEM_UNDO;
	// V(pronum)
	sops[3].sem_num = 0;
	sops[3].sem_op = 1;
	sops[3].sem_flg = SEM_UNDO;
	// V(space)
	sops[4].sem_num = 1;
	sops[4].sem_op = 1;
	sops[4].sem_flg = SEM_UNDO;
	// V(lock)
	sops[5].sem_num = 2;
	sops[5].sem_op = 1;
	sops[5].sem_flg = SEM_UNDO;
	while (1)
	{

		// P(lock);
		semop(semid, &sops[2], 1);
		// P(space);
		semop(semid, &sops[1], 1);

		
		fgets(ptr, 1024, stdin);

		// V(pronum);
		semop(semid, &sops[3], 1);
		// V(lock);
		semop(semid, &sops[5], 1);
	}
	semctl(semid, 0, IPC_RMID);
}